//
//  main.c
//  C_11网络与套接字
//
//  Created by Robin on 16/3/21.
//  Copyright © 2016年 cnbm. All rights reserved.
//

#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <netdb.h>
/**
 BLAB (绑定,监听,接受,开始通信)
 */

void error (char *msg){
    printf("%s : %s\n",msg,strerror(errno));
    exit(1);
}

// 打开套接字
int open_listener_socket(){
    int s = socket(PF_INET, SOCK_STREAM, 0);
    if (s == -1) {
        error("Cannot open the socket");
    }
    
    return s;
}

// 绑定套接字
void bind_to_port (int socket,int port){
    
    struct sockaddr_in name;
    name.sin_family = PF_INET;
    name.sin_port = (in_port_t)htons(30000);
    name.sin_addr.s_addr = htonl(INADDR_ANY);
    
    int reuse;
    if (setsockopt(socket, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(int)) == -1) {
        error("Cannot set the reuse option on socket");
    }
    
    int c = bind( socket, (struct sockaddr *)&name, sizeof(name));
    if (c == -1) {
        error("绑定端口失败");
    }
}

// 向客户端发送消息
int say (int socket, char *msg){
    int result = send(socket, msg, strlen(msg), 0);
    if (result == -1) {
        fprintf(stderr, "和客户端通信发生错误");
    }
    
    return result;
}

// 从客户端读取字符串
int read_in (int socket,char *buf,int len){
    
    char *s = buf;
    int slen = len;
    
    int c = recv(socket, s, slen, 0);
    
    while (c > 0 && s[c-1] != '\n') {
        s += c;
        slen -= c;
        c = recv(socket, s, slen, 0);
    }
    
    if (c < 0) {
        return c;
    }else if (c == 0){
        buf[0] = '\0';
    }else
        s[c-1] = '\0';
    
    return len-slen;
}

int catch_sigal (int sig,void(*handle)(int)){
    
    struct sigaction action;
    action.sa_handler = handle;
    action.sa_flags = 0;
    sigemptyset(&action.sa_mask);
    return sigaction(sig, &action, NULL);
}

int listener_d;

void handle_shutDown (int sig){
    
    if (listener_d) {
        close(listener_d);
    }
    
    fprintf(stderr, "Good bye!\n");
    exit(1);
}

void client_socket (){
    // 创建套接字
    //int s = socket(PF_INET, SOCK_STREAM, 0);
    
//    // 208,201,239,100:80 创建一个套接字地址
//    struct sockaddr_in si;
//    memset(&si, 0, sizeof(si));
//    si.sin_family = PF_INET;
//    si.sin_addr.s_addr = inet_addr("208,201,239,100");
//    
//    si.sin_port = htons(80);
//    connect(s, (struct sockaddr *)&si, sizeof(si));
    
    //
    struct addrinfo *res;
    struct addrinfo hits;
    memset(&hits, 0, sizeof(hits));
    
    hits.ai_family = PF_UNSPEC;
    hits.ai_socktype = SOCK_STREAM;
    getaddrinfo("www.oreilly.com", "80", &hits, &res); // 创建 www.oreilly.com 地址 80 端口的名字资源
    
    int s = socket(res->ai_family, res->ai_socktype, res->ai_protocol); // 利用名字资源创建套接字
    // res->ai_addr: 远程主机加端口号地址  ai_addrlen: 地址在存储器中的长度
    connect(s, res->ai_addr, res->ai_addrlen); // 连接远程套接字
    freeaddrinfo(res);
}


int main(int argc, const char * argv[]) {
    
    if (catch_sigal(SIGINT, handle_shutDown))
        error("Cannot set the interrupt handle\n");
    
    listener_d = open_listener_socket();
    bind_to_port(listener_d, 30000);
    
    if (listen(listener_d, 10))
        error("Cannot listen\n");
    
    struct sockaddr_storage client_addr;
    unsigned int addr_size = sizeof(client_addr);
    puts("Waiting for connection...");
    
    char buf[255];
    
    while (1) {
        // 等候监听
        int connect_d = accept(listener_d, (struct sockaddr *)&client_addr, &addr_size);
        if (connect_d == -1)
            error("Cannot open secondary socket\n");
        
        if (!fork()) {  //创建子进程 如果fork()调用返回0 就说明你在子进程中
            
            close(listener_d); // 在子进程中需要关闭主监听套接字 服务器只用 connect_d 套接字和客户端通信
            
            if (say(connect_d, "Internet Knock-Knock Procotol Server\r\nVersion1.0\r\nKnock! Knock!\r\n>") != -1) {
                read(connect_d, buf, sizeof(buf));
                
                if (strncasecmp("Who's there?", buf,12)) {
                    say(connect_d, "You should say 'Who's there?'!");
                }else{
                    
                    if (say(connect_d, "Oscar\r\n>") != -1) {
                        read(connect_d, buf, sizeof(buf));
                        if (strncasecmp("Oscar who?", buf,10)) {
                            say(connect_d, "You should say 'Oscar who?' !\r\n");
                        }else{
                            say(connect_d, "Oscal silly question,you get a silly answer\r\n");
                        }
                    }
                }
                
            }
            
            close(connect_d); // 关闭我们用来对话的副套接字 一旦通信结束,子进程就可以关闭通信套接字
            exit(0);          // 通信结束子进程退出程序,这样就能防止子进程进入服务器主循环
        }
//         GET /wiki/O'Reilly_Media http/1.1
//         Host: en.wikipedia.org
        close(connect_d);
    }
    
    return 0;
}
